package com.demo.api.conf;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author: cja
 * @date: 2019/11/13 19:37
 */
@Configuration
public class DataSourceConf {
    @Bean(name="primaryDataSource", destroyMethod = "close")
    @Qualifier("primaryDataSource")
    public DataSource druidDataSource(@Value("${spring.datasource.url}") String url,
                                      @Value("${spring.datasource.driver-class-name}") String driver,
                                      @Value("${spring.datasource.username}") String username,
                                      @Value("${spring.datasource.password}") String password) throws Exception{
        DruidDataSource drds = new DruidDataSource();
        drds.setUrl(url);
        drds.setDriverClassName(driver);
        drds.setUsername(username);
        try {
            drds.setPassword(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        drds.setMaxActive(300);
        drds.setInitialSize(6);
        drds.setMaxWait(60000);
        drds.setTimeBetweenEvictionRunsMillis(60000);
        drds.setMinEvictableIdleTimeMillis(300000);
        drds.setValidationQuery("SELECT '*' ");
        drds.setMaxOpenPreparedStatements(20);
        drds.setTestOnBorrow(true);
        drds.setTestWhileIdle(true);
        drds.setRemoveAbandoned(false);
        drds.setLogAbandoned(false);
        try {
            drds.setFilters("stat");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return drds;
    }
}
